import java.util.Random;
import java.net.*;
import java.io.*;

public class Table 
{
	private static Dealer dealer;
	private static int maxPlayers, startChips, smallBlind;//port, round
	private static int dealerButton;
	private static Random generator = new Random();
	private static ServerSocket[] serverSockets;
	
	public static void main(String args[])
	{
		try
		{
			startChips = Integer.parseInt(args[0]);
			smallBlind = Integer.parseInt(args[1]);
			maxPlayers = Integer.parseInt(args[2]);
			dealer = new Dealer(startChips, smallBlind, maxPlayers);
			serverSockets = new ServerSocket[maxPlayers];
			for(int i = 0; i < maxPlayers; i++)
				serverSockets[i] = new ServerSocket(Integer.parseInt(args[3 + i]));
		}
		catch(NumberFormatException e)
		{
			System.out.println("Bledne dane");
			System.exit(0);
		}
		catch(IOException e)
		{
			System.out.println("Nie moglem stworzyc serwera");
			System.exit(0);
		}
		
		for(ServerSocket t : serverSockets)
		{
			Socket temp;
			
			try
			{
				temp = t.accept();
			}
			catch(IOException e)
			{
				System.out.println("Błąd");
				return;
			}
			try
			{
				BufferedReader temp1 = new BufferedReader(new InputStreamReader(temp.getInputStream()));
				PrintWriter temp2 = new PrintWriter(temp.getOutputStream(), true);
				
				String line = "EMPTY EMPTY";
				String[] help = line.split("-");
				String name = "";
				while(!help[0].equals("NAME")) 
				{
			        	line = temp1.readLine();
					help = line.split("-");
			        	System.out.println(line);
					temp2.println("MONEY-"+ args[0]);
					if(help[0].equals("NAME"))
						name = help[1];
				}
				System.out.println("Podlaczono gracza " + name);
				dealer.createPlayer(name, temp2, temp1, true);
			}
			catch(IOException e)
			{
				System.out.println("Nie udalo sie stworzyc strumieni");
			}
		}
		while(true)
		{
			System.out.println("Nowa runda");
			startGame();
			dealer.reset();
		}
	}
	
	private static void startGame()
	{
		System.out.println("Nowa gra!");
		Random generator = new Random();
		int dealerButton = generator.nextInt(maxPlayers); //losowanie pozycji dealer buttona do pierwszej rundy
		dealer.giveCards();
		for(int round = 0; round<=3; round++)
		{
			if(round < 3)
			{
				if (round == 1) dealer.saveNrPlayers(); // zachowuje dla All-ina kto wszedl po pierwszej rundzie
				dealer.startAuction(dealerButton, round);
				if (dealer.getIsFinish())
				{
					System.out.println("Ktos wygral licytacje!");
					dealer.giveToWinner(dealer.whoWin());
					break;
				}
				System.out.println("Teraz bedziemy wymieniac karty!");
				dealer.startChanging(dealerButton);
			}
			else
			{
				System.out.println("Ostatnia runda!");
				dealer.startAuction(dealerButton, round);
				dealer.giveToWinner(dealer.whoWin());
			}
		}
	}
}
